import { Injectable } from '@angular/core';
import { Headers, Http } from "@angular/http";
import 'rxjs/add/operator/toPromise';

import { Hero } from '../Hero/hero';

@Injectable()
export class HeroService {

	private heroesUrl = 'api/heroes';
	private headers = new Headers({ 'Content-Type': 'application/json' });

	constructor(
		private http: Http
	) { }

	getHeroes(): Promise<Hero[]> {
		return this.http.get(this.heroesUrl)
			.toPromise()
			.then(response => {
				console.log('输出请求的Heroes', response)
				return response.json().data as Hero[]
			})
			.catch(this.handleError)
	}

	getHero(id: number): Promise<Hero> {
		const url = `${this.heroesUrl}/${id}`;
		return this.http.get(url)
			.toPromise()
			.then(response => {
				console.log('输出请求的Hero', response);
				return response.json().data as Hero;
			})
			.catch(this.handleError)
	}

	update(hero: Hero): Promise<Hero> {
		const url = `${this.heroesUrl}/${hero.id}`;
		return this.http.put(url, JSON.stringify(hero), { headers: this.headers })
			.toPromise()
			.then(() => hero)
			.catch(this.handleError)
	}

	create(name: string): Promise<Hero> {
		let data = {
			name:name
		}
		return this.http
			.post(this.heroesUrl, JSON.stringify(data), {headers:this.headers})
			.toPromise()
			.then(res => res.json().data as Hero)
			.catch(this.handleError)
	}
	
	delete(id: number): Promise<void> {
		const url = `${this.heroesUrl}/${id}`;
		return this.http
			.delete(url, {headers:this.headers})
			.toPromise()
			.then(() => null)
			.catch(this.handleError)
	}
		
	private handleError(error: any): Promise<any> {
		console.error('请求数据出错', error); // for demo purposes only
		return Promise.reject(error.message || error);
	}


}
